from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from groupevents.models import Events, Event_Comment, Event_Rsvp
from contifyuser.models import Member
from groupevents.forms import CreateEventForm, PostEventCommentForm
import StartGroup.Constants
import Constants
import connectpeople.Constants
import datetime
import utils.signals
from django.contrib.auth.models import User
from groupMembers.models import Member_Group, group_mem_assoc_v
import simplejson
from django.http import HttpResponse
from django.core.paginator import Paginator
import threading
from utils import activity_module, common_methods, common_query

# render form for creating a new event
def CreateNewEventForm(request, group_web_address):
    group_web_addr = group_web_address
    
    # Get group info
    group = getGroupInfo(group_web_addr)
    
    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)    
    
    # Create New Event form initialization
    create_event_form = CreateEventForm()
    return render_to_response(Constants.groupevents + Constants.create_new_event_template,
                              {Constants.create_event_form_constant: create_event_form,
                               'event': None, 'group':group, 'permission':permission},
                              context_instance = RequestContext(request))
    

# render new event confirmation
def CreateNewEvent(request, group_web_address):
    group_web_addr = group_web_address
    userid = request.session[connectpeople.Constants.session_userid]
    group = getGroupInfo(group_web_addr)
    
    if request.method == 'POST':

        # Get email ids of these users
        recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.create_event_email_flag_constant)
        
        # Compose subject for the email
        subj = group.group_name + " - New Event Created"
        if 'event_id' in request.session:
            # Get info values if exist
            event_info = Events.objects.get(id=request.session['event_id'])
            event_info.event_name = request.POST.__getitem__('event_name')
            event_info.event_place = request.POST.__getitem__('event_place')
            
            # Since data is coming in string format. split and put in date format
            event_date_split = request.POST.__getitem__('event_date').split('/', 2)
            
            try:
                event_info.event_date = datetime.date(int(event_date_split[2]), int(event_date_split[0]), int(event_date_split[1]))
            except:
                print "Date not update"
            event_info.event_desc = request.POST.__getitem__('event_desc')
            event_info.save()
            
            # Compose subject for the email
            subj = event_info.event_name + " event updated"
            # Send Email alerts. Use threading to speed up things
            new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Events, 'a_email':recipient_list, 'a_model':event_info, 'a_subject':subj, 'a_template':"email/eventUpdatedEmail.html"})
            new_comment_thread.setDaemon(True)
            new_comment_thread.start()
        else:
            # Create New Event form initialization
            create_event_form = CreateEventForm(data=request.POST)
            if create_event_form.is_valid():
                new_event = create_event_form.save(userid, group)
                
                # New Event Activity save 
                activity_module.setActivityNode(new_event.event_name, userid, group_web_addr, connectpeople.Constants.create_event_action)                    
                
                # Send the confirmation email to members of the group
                # Use threading. so that user don't have to wait for email process to finish up
                new_event_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Events, 'a_email':recipient_list, 'a_model':new_event, 'a_subject':subj, 'a_template':"email/createEventEmail.html"})                    
                new_event_thread.setDaemon(True)
                new_event_thread.start()
    
    # Return to home page
    return redirect('/connectpeople/group/' +group_web_addr + '/')
    
# render group event view
def event_view(request, group_web_address, id):
    # Get events object
    event = Events.objects.get(id=id)
    
    userid = request.session[connectpeople.Constants.session_userid]
    user = getUserInfo(userid)
    member = getMemberInfo(user)
    group_web_addr = group_web_address
    group = getGroupInfo(group_web_addr)
    userRsvpRow = getUserRsvp(event, userid)

    # Save/Delete comment if posted
    if request.method == 'POST':
        #  Get the rsvp value
        try:
            rsvp = request.POST.__getitem__('rsvp')
        except:
            # If attribute not defined then request has come
            # to add new comment
            rsvp = None
        
        if rsvp:
            save_rsvp(event,userid,rsvp)
            
            # Event RSVP Activity save 
            activity_module.setActivityNode(event.event_name, userid, group_web_addr, connectpeople.Constants.rsvp_event_action)             
            
            # Get email ids of these users
            recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.event_rsvp_email_flag_constant)
            # Compose subject for the email
            subj = event.event_name + " event - New RSVP "
            # Send Email alerts. Use threading to speed up things
            new_event_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Events, 'a_email':recipient_list, 'a_model':event, 'a_subject':subj, 'a_template':"email/newEventRsvpEmail.html"})
            new_event_thread.setDaemon(True)
            new_event_thread.start()
            
            # Set response to success
            response = simplejson.dumps({'success':'success'})
        else:
            # Get the comment id to be deleted
            try:
                commid = request.POST.__getitem__('commid')
            except:
                # If attribute not defined then request has come
                # to add new comment
                commid = None
                
            if commid:
                # Delete the comment from database
                Event_Comment.objects.get(id=commid).delete()
                # Set response to success
                response = simplejson.dumps({'success':'success'})
            else:
                # Post New Event Comment form initialization
                post_event_comment_form = PostEventCommentForm(data=request.POST)
                if post_event_comment_form.is_valid():           
    
                    # Save the form
                    post_event_comment_form.save(event, member.user.username, member.photo)
                    
                    # Event Comment Activity save 
                    activity_module.setActivityNode(event.event_name, userid, group_web_addr, connectpeople.Constants.comment_event_action)                      
                    
                    # Update last updated values
                    #updateEventLastUpdate(event, member.first_name)
                    # Get email ids of these users
                    recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.event_comment_email_flag_constant)
                    # Compose subject for the email
                    subj = event.event_name + " event - New Comment Posted"
                    # Send Email alerts. Use threading to speed up things
                    new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Events, 'a_email':recipient_list, 'a_model':event, 'a_subject':subj, 'a_template':"email/newEventCommentEmail.html"})
                    new_comment_thread.setDaemon(True)
                    new_comment_thread.start()                    
                    
                    
                    # Recent comment info
                    rec_post_dt = datetime.datetime.now().strftime('%Y, %b, %d')
                    rec_comment = request.POST
                    recentPost = {'rpd': rec_post_dt, 'rc': rec_comment}
                    # Set response to same input comment value
                    response = simplejson.dumps(recentPost)
            

    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
  
    # Post New Comment form initialization
    post_event_comment_form = PostEventCommentForm()
    
    comments = getComments(event)
    comments_list = geCommentsList(comments)
    paginator = Paginator(comments_list, 10)

    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)

    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)    
    
    return render_to_response("groupevents/event_view.html",
                              {'event': event, 'post_event_comment_form': post_event_comment_form,
                               'pages': pages, 'curr_member': member, 'curr_date': datetime.date.today(),
                               'rsvp_row': userRsvpRow, 'group':group,'permission':permission},
                              context_instance = RequestContext(request))
    
# Render Event form to edit
def edit_event(request, group_web_address, id):
    # Save event id to session
    request.session['event_id'] = id
    
    # Get Events object
    event = Events.objects.get(id=id)
    
    # Get group info
    group = getGroupInfo(group_web_address)         
    
    # Create New Event form initialization
    create_event_form = CreateEventForm()
    
    userid = request.session[connectpeople.Constants.session_userid]    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)
    
    return render_to_response(Constants.groupevents + Constants.create_new_event_template,
                              {Constants.create_event_form_constant: create_event_form,
                               'event': event, 'group':group, 'permission':permission},
                              context_instance = RequestContext(request))

# Save rsvp
def save_rsvp(event_info, userid, rsvp):
    # Get rsvp if user already rsvped to the event
    rsvp_row = getUserRsvp(event_info, userid)        
    if rsvp_row:
        rsvp_row.rsvp_val = rsvp
        rsvp_row.save()
    else:
        eventRsvp = Event_Rsvp(event=event_info, user_id = userid, rsvp_val = rsvp, response_date = datetime.datetime.now())
        eventRsvp.save()
    
# Get User's RSVP value for the event
def getUserRsvp(event_info, userid):
    try:
        rsvp_row = Event_Rsvp.objects.get(event=event_info, user_id=userid)
    except:
        rsvp_row = None
    return rsvp_row

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)
    
# Get All the members associated with the group
def getGroupMembersUserIds(group_web_addr):
    return group_mem_assoc_v.objects.filter(group_web_address = group_web_addr).order_by('-join_date').values_list('userid', flat=True)

# Get the list of email confirmation recipients
def getRecipientList(user_list):
    recipient_list = []
    if user_list is not None:
        for each in user_list:
            recipient_list.append(each.email)
    
    return recipient_list

# Helper function to obtain Comments related to the Discussion
def getComments(event_info):
    return Event_Comment.objects.filter(event = event_info).order_by('-post_date')
    
# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)
    
# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)

# Helper function to obtain Comments in a list format
def geCommentsList(event_comments):
    num_posts = 0
    event_comments_list = []
    if event_comments is not None:
        for each in event_comments:
            event_comments_list.append(each)
    
    return event_comments_list
    